﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;

namespace CIAWorldMap
{
    public static class ArchiveLoader
    {
        /*

    RC	Region Code - tinyint(1).  A code that determines the character mapping used in the Full_Name field:
        1 = Western Europe/Americas;
        2 = Eastern Europe;
        3 = Africa/Middle East;
        4 = Central Asia;
        5 = Asia/Pacific;
        6 = Vietnam.
    UFI	Unique Feature Identifier - int(4).  A number which uniquely identifies the feature.
    UNI	Unique Name Identifier - int(4).  A number which uniquely identifies a name.
    LAT	Latitude of the feature in ± decimal degree:
        no sign (+) = North;
        negative sign (-) = South.
    LONG	Longitude of the feature in ± decimal degree:
        no sign (+) = East;
        negative sign (-) = West.
    UTM	Universal Transverse Mercator - char(4) coordinate grid reference.
    JOG	Joint Operations Graphic - char(7) reference.
    FC	Feature Classification - char(1:
        A = Administrative region;
        P = Populated place;
        V = Vegetation;
        L = Locality or area;
        U = Undersea;
        R = Streets, highways, roads, or railroad;
        T = Hypsographic;
        H = Hydrographic;
        S = Spot feature.
    DSG	Feature Designation Code - char(5).  A two to five-character code used to identify the type of feature a name is applied to.
    PC	Populated Place Classification - tinyint(1).  A graduated numerical scale denoting the relative importance of a populated place.  The scale ranges from 1,  relatively high, to 5, relatively low.
    CC1	Primary Country Code - char(2).  A two alphabetic character code uniquely identifying a geopolitical entity (countries, dependencies, and areas of special sovereignty).
    ADM1	First-order administrative division - char(2).  A two alphanumeric character code uniquely identifying a primary administrative division of a country, such as a state in the United States.
    ADM2	Second-order administrative division - varchar(255).  A subdivision of a first-order administrative division, such as a county in the United States.
    DIM	Dimension - int(4).  Usually used to display elevation or population data.
    CC2	Secondary Country Code - char(2).  A two alphabetic character code uniquely identifying the country code of a particular name if different than that of the feature.
    NT	Name Type - char(1):
        C = Conventional;
        D = Dagger or not verified;
        N = Native;
        V = Variant or alternate.
    LC	Language Code - char(2).  A two alphabetic character code uniquely identifying a language of  a country if multiple official languages are used.
    SHORT_FORM	varchar(128) - A specific part of the name that could substitute for the full name.
    GENERIC	varchar(128) - The descriptive part of the full name (does not apply to populated place names).
    SORT_NAME)	varchar(200) - A form of the full name which allows for easy sorting of the name into alpha-numeric sequence.  It is comprised of the specific name, generic name, and any articles or prepositions. This field is all upper case with spaces, diacritics, and hyphens removed and numbers are substituted with lower case alphabetic characters. It is in reading order.
    FULL_NAME	varchar(200) - The full name is a complete name which identifies the named feature.  It is comprised of  the specific name, generic name, and any articles or prepositions. It is in reading order.
    FULL_NAME_ND	varchar(200) - Same as the full name but the diacritics and special characters are substituted with Roman characters.   ND = No Diacritics / Stripped Diacritics.
    URL	Uniform Resource Locator.  The URL is tied to the UFI of a record and points to that record in the GEOnet Names Server (GNS) on NIMA's public WWW server.
       
        
        */

        public static void ReadBoundaries(Dictionary<string, MapSegment> normalSegments, LaosBorder laosBorder)
        {
            const string f = @"C:\laomapdata\asia.bin";

            normalSegments.Clear();

            using (TextReader tr = new StreamReader(f))
            {
                var c = new char[0xe00];
                tr.ReadBlock(c, 0, 0xe00);
                string line;

                MapSegment curentSeg = null;
                while (true)
                {
                    line = tr.ReadLine();
                    if (line == null)
                        break;

                    if (line.StartsWith("se"))
                    {
                        curentSeg = new MapSegment();
                        if (!IsLaosBorderSegmentSaveInLaosBorder(line, laosBorder, curentSeg))
                        {
                            if (!normalSegments.ContainsKey(line))
                            {
                                normalSegments.Add(line, curentSeg);
                            }
                        }
                        continue;
                    }

                    line = line.Replace("\t", "");
                    line = line.Replace("W", " ");
                    string[] cells = line.Split(' ');

                    if (curentSeg != null && cells.Count() >= 2 && cells.Count() < 15)
                    {
                        double lon = double.Parse(cells[1]);
                        if (lon > 99)
                        {
                            curentSeg._coords.Add(new Coord(double.Parse(cells[0]), lon));
                        }
                    }
                }
            }

            laosBorder.LaosBorderSetSgments();
        }

        // decide where to put this segment. - if it's a Laos border - put it elsewhere
        private static bool IsLaosBorderSegmentSaveInLaosBorder(string line, LaosBorder laosBorder,   MapSegment curentSeg)
        {
            if (!line.Contains("rank 1 ")) // A border???
                return false;
      
                // destined for LaosBorder
            if (laosBorder.AddBorder(curentSeg, line))
                return true;
        
            // not a Laos border 
            return false;
        }

        public static void Decompress(string f)
        {

            // Get the stream of the source file.
            using (FileStream inFile = new FileStream(f, FileMode.Open, FileAccess.Read))
            {
                // Get original file extension, for example
                // "doc" from report.doc.gz.

                //Create the decompressed file.
                using (FileStream outFile = File.Create(@"C:\temp\crap.txt"))
                {
                    using (var decompress = new GZipStream(inFile,
                            CompressionMode.Decompress))
                    {
                        // Copy the decompression stream 
                        // into the output file.

                        // part of .NET 4.0
                       // decompress.CopyTo(outFile);

                        Console.WriteLine("Decompressed: {0}", f);

                    }
                }
            }
        }

    }
}

